<?php
/**
 * 图片画册
 * AUTHOR  : zlf
 * DateTime: 2022/06/18 09:00
 */
namespace App\V3\V3_2\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\V3\V3_2\Services\TextImageService;
use App\V3\V3_2\Services\TextImageTemplatesService;
use OSS\OssClient;
use Illuminate\Support\Facades\DB;
use App\V3\V3_2\Models\AdminAddendumModel;
use App\V3\V3_2\Services\ContentTagsService;

class TextImageController extends BaseController
{
    protected $ossClient;
    public function __construct(Request $request){
        parent::__construct($request);
        $this->ossClient=new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
            );
    }

    /**
     * 添加文字图片画册
     * @param p_a_name
     * @param mobile
     * @param album_cover_img
     * @param background_music
     */
    public function addTextImage(Request $request){
        $adminInfo   = AdminAddendumModel::select('is_vip')->where(['main_id'=>$this->getMainUserId()])->first()->toArray();

        if(!empty($adminInfo) && in_array($adminInfo['is_vip'],[1,2])){
            /*
             if($adminInfo['one_key_album_times'] != -1 && $total_num >= $adminInfo['one_key_album_times']){

             return $this->fail('','您一键生成商品画册次数，已达到设置数量！');
             }

             if($adminInfo['album_amount'] != -1 && $total_num >= $adminInfo['album_amount']){

             return $this->fail('','您生成商品画册彩页，已达到设置数量！');
             } */

        }else{

            return $this->fail('','您还不是VIP会员，还不能创建文字画册！');
        }
        $data = $request->all();
        $imgs_data=self::handleImgsData($this->ossClient,$request,$this->getMainUserId());// 处理图片画册 封面、音乐 函数
       if ($imgs_data['code'] === 0){
        $imgs_data = $imgs_data['data'];
        }else{
        return response()->json($imgs_data);
        }

        $data['create_time'] = time();
        $data['update_time'] = time();

        $data = array_merge($data,$imgs_data);

        $data['user_id']     = $this->getUserId();
        $data['main_id']     = $this->getMainUserId();
        DB::beginTransaction();
        try {
            $id=TextImageService::addTextImage($data);
            if($id){
                $cData = [];
                $cData['is_top']       = 1;
                $cData['sort_number']  = 0;
                $cData['pa_id']        = $id;
                $cData['create_time']  = time();
                $cData['content_tags'] = '首页封面';
                $cData['user_id']      = $this->getUserId();
                $cData['main_id']      = $this->getMainUserId();

                ContentTagsService::addContentTags($cData);//同时创建首页封面标签

                DB::commit();
                $this->log('文字图片画册,添加成功', $id);
                return response()->json(['code' => 0,'msg'  => '添加成功','data' => ['album_id'=>$id]]);

            }else{

                return response()->json(['code' => 1,'msg'  => '添加失败','data' => ""]);
            }

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 1,'msg'  => $e->getMessage(),'data' => ""]);
        }
    }
    /**
     * 删除文字图片画册
     * @param pa_ids  文字图片画册id（多个用逗号分割）
     */
    public function delTextImage(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pa_ids'          => 'required'
        ],
            [
                'pa_ids.required' => '缺少参数，文字画册id'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {

            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }

        $condition['user_id'] = $this->getUserId();

        $data['pa_ids'] = explode(',',$data['pa_ids']);

        $res = TextImageService::getTextImageInfos($condition, $data['pa_ids']);

        if(empty($res)){

            return response()->json(['code' => 1,'msg'  => '要删除的文字画册，没找到!','data' => '']);
        }
        DB::beginTransaction();
        try {

            $bool = TextImageService::delTextImage($condition,$data['pa_ids']);

            if($bool){

                foreach ($res as $tk=>$tv){
                    //删除oss里的文件
                    self::delOssFilePath($tv['album_cover_img'], $this->ossClient, $this->getMainUserId());
                    //删除oss里的文件
                    self::delOssFilePath($tv['background_music'], $this->ossClient, $this->getMainUserId());

                }

                $t_res = TextImageTemplatesService::getTextImageTemplatesInfos($condition, $data['pa_ids']);

                if(!empty($t_res)){
                 //删除画册对应的内容模板
                 TextImageTemplatesService::delContentTempLates($condition, $data['pa_ids']);

                foreach ($t_res as $tik=>$tiv){

                    if(!empty($tiv['temp_img_video_01'])){

                        $tiv['temp_img_video_01'] = explode(",",$tiv['temp_img_video_01']);

                        foreach ($tiv['temp_img_video_01'] as $iv1k =>$iv1v){//删除素材1的文件
                            //删除oss里的文件
                            self::delOssFilePath($iv1v, $this->ossClient, $this->getMainUserId());
                        }
                      }
                      if(!empty($tiv['temp_img_video_02'])){//删除素材2的文件

                          $tiv['temp_img_video_02'] = explode(",",$tiv['temp_img_video_02']);

                          foreach ($tiv['temp_img_video_02'] as $iv2k =>$iv2v){
                            //删除oss里的文件
                            self::delOssFilePath($iv2v, $this->ossClient, $this->getMainUserId());
                        }
                      }
                    }
                }

                DB::commit();
                $this->log('文字图片画册,删除成功', $bool);
                return response()->json(['code'=>0,'msg'=>'删除成功','data'=>'']);
            }else{
                return response()->json(['code'=>1,'msg'=>'删除失败','data'=>'']);
            }

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code'=>1,'msg'=>$e->getMessage(),'data'=>'']);
        }
    }

    /**
     * 修改文字图片画册
     * @param pa_id
     * @param p_a_name
     * @param mobile
     * @param album_cover_img
     * @param background_music
     */
    public function updateTextImage(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pa_id'          => 'required'
        ],
        [
            'pa_id.required' => '缺少参数，文字画册id'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {

            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }

        $condition['id']      = $data['pa_id'];
        $info=TextImageService::getTextImageInfo($condition);
        $delData = [];
        if(empty($info))
        return response()->json(['code'=>1,'msg'=>'没有找到，要修改的文字画册','data'=>'']);

        if(!empty($cover_img_files = $request->file('album_cover_img'))){

            $res = self::handlePicFormat($cover_img_files,'p','封面格式,不正确！');//判断文件格式

            if(!empty($res)) return $res;

            if($cover_img_files->isValid()){

                $img_path = $cover_img_files->store('huace/text/img/'.date('Y').'-'.date('m').'-'.date('d'));

                $imgRes = self::addOssUploadImg($this->ossClient,$this->getMainUserId(),$cover_img_files, $img_path);

                if($imgRes['code'] === 0){

                    $delData[] = 'album_cover_img';
                    $data['album_cover_img'] = $imgRes['data'];
                }else{
                    return response()->json($imgRes);
                }

            }else{

                return response()->json(['code' => 1,'msg' => '画册封面，上传失败！','data' => '']);
            }
        }
        if(!empty($cover_img_files = $request->file('background_music'))){

            $res = self::handlePicFormat($cover_img_files,'m','背景音乐格式,不正确！');//判断文件格式

            if(!empty($res)) return $res;

            if($cover_img_files->isValid()){

                $img_path = $cover_img_files->store('huace/text/music/'.date('Y').'-'.date('m').'-'.date('d'));

                $imgRes = self::addOssUploadImg($this->ossClient,$this->getMainUserId(),$cover_img_files, $img_path);

                if($imgRes['code'] === 0){

                    $delData[] = 'background_music';
                    $data['background_music'] = $imgRes['data'];
                }else{
                    return response()->json($imgRes);
                }


            }else{

                return response()->json(['code' => 1,'msg' => '背景音乐，上传失败！','data' => '']);
            }
        }
       DB::beginTransaction();
       try {
           unset($data['pa_id']);
           $bool = TextImageService::updTextImage($condition, $data);
           if($bool){

               if(!empty($delData)){
                   foreach ($delData as $dk=>$dv){
                        //删除oss里的文件
                        self::delOssFilePath($info[$dv], $this->ossClient, $this->getMainUserId());
                   }
               }
               DB::commit();
               return response()->json(['code'=>0,'msg'=>'编辑成功','data'=>'']);

           }else{
               return response()->json(['code'=>1,'msg'=>'编辑失败','data'=>'']);
           }

       } catch (\Exception $e) {
           DB::rollBack();
           return response()->json(['code'=>1,'msg'=>$e->getMessage(),'data'=>'']);
       }

    }

    /**
     * 更新文字图片画册封面或音乐
     * @param pa_id            文字图片画册id
     * @param old_path         原封面图片或背景音乐路径
     * @param album_cover_img  画册封面
     * @param background_music 背景音乐
     */
    public function updTextImageImgMusic(Request $request){
        //参数验证
        $validator = Validator::make($pdata = $request->all(), [
            'pa_id'    =>'required',
            'old_path' =>'required',
        ],
            [
                'pa_id.required'   => '缺必要参数，文字画册id',
                'old_path.required'=> '原画册封面or背景音乐路径，不能为空',
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {

            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }
            $flag = 'album_cover_img';

        if(!empty($request->file('background_music'))){

            $flag = 'background_music';
        }
            $data[$flag] = "";

        if(!empty($cover_img_files = $request->file($flag))){

            $res = self::handlePicFormat($cover_img_files,'p','封面格式,不正确！');//判断文件格式

            if(!empty($res)){

                return $res;
            }
            if($cover_img_files->isValid()){

                $img_path = $cover_img_files->store('huace/text/img/'.date('Y').'-'.date('m').'-'.date('d'));
                $imgRes   = self::addOssUploadImg($this->ossClient,$this->getMainUserId(),$cover_img_files, $img_path);

                if($imgRes['code'] === 0){

                    $data[$flag] = $imgRes['data'];
                }else{
                    return response()->json($imgRes);
                }

            }else{

                return response()->json(['code' => 1,'msg' => '画册封面，上传失败！','data' => '']);
            }
        }

        if(!empty($cover_img_files = $request->file($flag))){

            $res = self::handlePicFormat($cover_img_files,'m','背景音乐格式,不正确！');//判断文件格式

            if(!empty($res)){

                return $res;
            }

            if($cover_img_files->isValid()){

                $img_path = $cover_img_files->store('huace/text/music/'.date('Y').'-'.date('m').'-'.date('d'));

                $imgRes   = self::addOssUploadImg($this->ossClient,$this->getMainUserId(),$cover_img_files, $img_path);

                if($imgRes['code'] === 0){

                    $data[$flag] = $imgRes['data'];
                }else{
                    return response()->json($imgRes);
                }

            }else{

                return response()->json(['code' => 1,'msg' => '背景音乐，上传失败！','data' => '']);
            }
        }
        if(!empty($data[$flag])){

            $condition['id']      = $pdata['pa_id'];
            $condition['user_id'] = $this->getUserId();

            $bool = TextImageService::updTextImage($condition,$data);

            if($bool){

                if(is_file(public_path($pdata['old_path']))){

                    unlink(public_path($pdata['old_path']));
                }
                $this->log('更新文字图片画册封面或音乐,更新成功', $bool);
                return response()->json(['code'=>0,'msg'=>'更换成功','data'=>$data]);
            }
        }

        return response()->json(['code'=>1,'msg'=>'更换失败','data'=>'']);

    }

    /**
     * 查询文字画册列表
     * @param curr_page 页码
     */
    public function getTextImageList(Request $request){

        $condition['ti.main_id'] = $this->getMainUserId();
        $currentPage = !empty($request->input('curr_page'))?$request->input('curr_page'):1;
       $pageSize = !empty($request->input('page_size'))?$request->input('page_size'):20;
        $list = TextImageService::getTextImageList($condition, $currentPage,$pageSize);

        if(!empty($list['data'])){
               foreach ($list['data'] as $k=>$val){
                $list['data'][$k]['create_time']=date('Y-m-d H:i:s',$val['create_time']);
                $list['data'][$k]['update_time']=date('Y-m-d H:i:s',$val['update_time']);

                if(!empty($val['album_cover_img'])){

                    $list['data'][$k]['album_cover_img'] = self::addWatermark($this->ossClient,$val['album_cover_img'], $this->getMainUserId());
                }
               }
           }

        $this -> log('文字图片画册，查询成功', $list);

        return response()->json(['code'=>0,'msg'=>'查询成功','data'=>$list]);


    }

     /**
      * 查询文字画册信息
      * @param pa_id 文字画册id
      */
    public function getTextImageInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pa_id'          => 'required'
        ],
            [
                'pa_id.required' => '缺少参数，文字画册id'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {

            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }

        $condition['id']      = $data['pa_id'];
        $condition['main_id'] = $this->getMainUserId();

        $info = TextImageService::getTextImageInfo($condition);

        if(!empty($info)){
            if(!empty($info['album_cover_img'])){

                $$info['album_cover_img'] = self::addWatermark($this->ossClient,$info['album_cover_img'], $this->getMainUserId());
            }
            $this->log('查询文字画册信息,查询成功', $info);
            return response()->json(['code' =>0,'msg'  => '查询成功','data' => $info]);
        }else{

            return response()->json(['code' => 1,'msg'  => '查询失败','data' => '']);
        }

    }
    /**
     * 处理图片画册 封面、音乐 函数
     *
     */
    static public function handleImgsData($client,$request,$mainId){

        $data = [];
        $data['album_cover_img']  = "";
        $data['background_music'] = "";

        if(!empty($cover_img_files = $request->file('album_cover_img'))){

            $res = self::handlePicFormat($cover_img_files,'p','封面格式,不正确！');//判断文件格式

            if(!empty($res)) return $res;

            if($cover_img_files->isValid()){

                $imgPath  = $cover_img_files->store('huace/text/img/'.date('Y').'-'.date('m').'-'.date('d'));

                $imgRes   = self::addOssUploadImg($client,$mainId,$cover_img_files, $imgPath);

                if($imgRes['code'] === 0){

                    $data['album_cover_img'] = $imgRes['data'];
                }else{
                    return $imgRes;
                }

            }else{
               return ['code' => 1,'msg' => '画册封面，上传失败！','data' => ''];
            }

        }elseif(!empty($request->input('album_cover_img'))){

            $data['album_cover_img'] = $request->input('album_cover_img');
        }

        if(!empty($music_files = $request->file('background_music'))){

            $res = self::handlePicFormat($music_files,'m','音乐格式,不正确！');//判断文件格式

            if(!empty($res)) return $res;

            if($music_files->isValid()){

                $music_path = $music_files->store('huace/text/music/'.date('Y').'-'.date('m').'-'.date('d'));

                $imgRes = self::addOssUploadImg($client,$mainId,$music_files, $music_path);

                if($imgRes['code'] === 0){
                    $data['background_music'] = $imgRes['data'];
                }else{
                    return $imgRes;
                }


            }else{
                return ['code' => 1,'msg' => '背景音乐，上传失败！','data' => ''];
            }
        }elseif(!empty($request->input('background_music'))){

                $data['background_music'] = $request->input('background_music');
        }
                return ['code' => 0,'msg' => 'success','data' => $data];
    }

    /**
     * 图片上传到oss系统
     * @param unknown $client
     * @param unknown $file
     */
    static public function addOssUploadImg($client,$mainId,$file,$path){
        $res = handleUploadFileType($file);
        if(!empty($res)) return $res;
        $size = $file -> getSize();
         $result = saveFileSize(['main_id'=>$mainId], $size,$path);
         if($result['code'] == 1) return $result;
        try {

            $fullPath = '/uploads/'.$path;
            $ossPath  = ltrim($fullPath,'./');
            $path     = public_path().$fullPath;
            $client -> uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
            @unlink($path);
            $url = config('app.aliyun_oss_bucket_url').$fullPath;
            return ["code"=>0,"msg"=>"success","data"=>$url];

        } catch (\Exception $e) {

            return ["code"=>1,"msg"=>"OSS系统，上传图片失败！","data"=>""];
        }
    }

    /**
     * 添加水印
     * @param unknown $file
     */
    static public function addWatermark($client,$file,$mainId){
        if(empty($file)) return $file;
        $adminInfo = AdminAddendumModel::select('clear_watermark_or_not')->where(['main_id'=>$mainId])->first();

        if($adminInfo['clear_watermark_or_not']==1){

            return $file;
        }else{

                $delPath = strstr($file, 'uploads/');
                $imgInfo = $client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
                if(strpos($imgInfo['content-type'],'image/') !== false){

                    return $file = $file.config('app.aliyun_oss_img_watermark');
                }

            return $file;
        }
    }
    /**
     * 删除oss里的文件
     * @param unknown $file
     * @param unknown $mainId
     */
    static public function delOssFilePath($file,$client,$mainId){
        if(empty($file)) return $file;
        DB::beginTransaction();
        try {
            $delPath = strstr($file, 'uploads/');
            $imgInfo=$client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
            AdminAddendumModel::where(['main_id'=>$mainId])
            ->decrement('file_total_size', $imgInfo['content-length']);
            $client -> deleteObject(config('app.aliyun_oss_bucket'), $delPath);
            DB::commit();
            } catch (\Exception $e) {
            DB::rollBack();
            return "";
            }
    }

    /**
     * 处理图片和视频格式
     */
    static public function handlePicFormat($files,$flag,$msg){

        $pic_video_format = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts,
                            flash,mpeg,mpeg-2,mpeg-4,midi,wmv,asf,asx,rm,rmvb,mp4,3gp,mov,m4v,avi,dat,mkv,flv,vob,
                            bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,
                            ufo,eps,ai,raw,wmf,webp,avif,apng';

        $pic_format       = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';

        $music_format     = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts';

        $ext = $files->extension();

        $ext = strtolower($ext);

        if($flag == 'm'){

            $pic_video_format_arr = explode(',',$music_format);

        }elseif($flag == 'p'){

            $pic_video_format_arr = explode(',',$pic_format);

        }else{

            $pic_video_format_arr = explode(',',$pic_video_format);
        }

        if (!in_array($ext, $pic_video_format_arr)) {

            return ['code' => 1,'msg' => $msg,'data' => ''];die;
        }
    }
}
